//
//  ViewController.swift
//  ddx0513
//
//  Created by jiang yongbin on 15/5/13.
//  Copyright (c) 2015年 jiang yongbin. All rights reserved.
//

import UIKit
import CoreData
var rootController:ViewController!

class ViewController: UIViewController {

   
    
  //  @IBOutlet weak var lineView: UIImageView!
    
    //@IBOutlet weak var AllCourse: UIButton!
    //@IBOutlet weak var LearningCourse: UIButton!
    //@IBOutlet weak var LearnedCourse: UIButton!
    
    
    @IBOutlet var ingridientView:UIView!
    
    @IBOutlet var container:UIScrollView!
    
    @IBOutlet weak var messageBtn:UIButton!
    
    var messageBadgeView:GJKBadgeView!

   // var button: GJKButtonWithBadge!

    //var  tagView:SKTagView!
    
    var allcourse:AllCourseViewController! = nil
    var learncourse:LearnCourse! = nil
    var finishedcourse:finishedCourse! = nil
   // var finishedCourse:finishedCourse == nil
    var loginviewcontroller: LoginViewController! = nil
    var classifyMenuViewController:CYLClassifyMenuViewController! = nil
    var  subMenu:CCSegmentedControl! = nil
    var  setting:SettingTableViewController! = nil
   // var subMenu:CCSegmentedControl! = nil
    
    var vw:UIView = UIView(frame: CGRectMake(0, 416 , UIScreen.mainScreen().bounds.size.width, 40))
    
    var containerSelected: UIViewController?
    

  //   var allcourse = UIStoryboard(name:"AllCourse", bundle:nil).instantiateInitialViewController() as! UIViewController
    
    
    
    @IBAction func SettingClick(sender: AnyObject) {
        
        if (DBUtils.mem.loginStatus) {
            setting = UIStoryboard(name: "Setting", bundle: nil).instantiateViewControllerWithIdentifier("Setting") as! SettingTableViewController

            rootController.navigationController?.pushViewController(setting,animated:true)
        } else {
            var viewController = UIStoryboard(name: "Login", bundle: nil).instantiateViewControllerWithIdentifier("Login") as! LoginViewController
            viewController.sourceNavi = false
            
            rootController.navigationController?.pushViewController(viewController,animated:true)
            self.navigationController?.setNavigationBarHidden(false, animated: true)

        }
        
        
    }
    
    
    @IBAction func MessageClick(sender: AnyObject) {
        
      //  messagebtn.badgeValue = 1
        var pushcontroller = UIStoryboard(name: "Push", bundle: nil).instantiateViewControllerWithIdentifier("push") as! PushTVController
        
        rootController.navigationController?.pushViewController(pushcontroller, animated:true)
        self.navigationController?.setNavigationBarHidden(false, animated: true)

    }

    
    
    
    
    @IBAction func SearchClick(sender: AnyObject) {
        

       // var controller:CYLSearchController = CYLSearchController.initwi
     
      //  CYLSearchController *controller = [[CYLSearchController alloc] initWithNibName:@"CYLSearchController" bundle:nil];
      //  controller.delegate = self;
      //  self.searchController = [[UINavigationController alloc] initWithRootViewController:controller];
    //    [controller showInViewController:self];
        
        
       var searchcontroller = UIStoryboard(name: "Search", bundle: nil).instantiateViewControllerWithIdentifier("SearchBar") as! SearchBarEmbeddedInNavigationBarViewController
     //   var searchcontroller = UIStoryboard(name: "Search", bundle: nil).instantiateViewControllerWithIdentifier("Search") as! SearchCourseTvController
        rootController.navigationController?.pushViewController(searchcontroller, animated:true)
         self.navigationController?.setNavigationBarHidden(false, animated: true)

    }
    
    
    override func viewWillAppear(animated: Bool)
    {
         messageBadgeView.value = 1
    }
    
     override func viewDidLoad() {
        super.viewDidLoad()
        //self.view.backgroundColor = UIColor.grayColor()
        //  super.viewDidDisappear(animated)
        
       // messagebtn = GJKButtonWithBadge(frame: CGRectMake(0,0,30,30))
        //button.badgeValue = 1
        
//        var settingItem = UIBarButtonItem(image: UIImage(named: "设置.png"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("SettingClick:"))
//        var messageItem = UIBarButtonItem(image: UIImage(named: "信息.png"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("MessageClick:"))
//        var searchItem = UIBarButtonItem(image: UIImage(named: "搜索.png"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("SearchClick:"))
//        self.navigationItem.rightBarButtonItems = [settingItem, messageItem, searchItem]
        
        //消息数提示
        messageBadgeView =  GJKBadgeView(frame: CGRectMake(messageBtn.frame.width - 6 , 2, 18, 18));
        messageBadgeView.value = 1
        messageBtn.addSubview(messageBadgeView)
        
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        rootController = self
        var h = CCSegmentedControl(items: ["全部课程","正在学习","已学完"])
        h.frame=CGRectMake(0, 64, UIScreen.mainScreen().bounds.size.width, 40)
        
        //设置背景图片，或者设置颜色，或者使用默认白色外观
        // h.backgroundImage = UIImage(named: "背景块.png")
        //阴影部分图片，不设置使用默认椭圆外观的stain
       // segmentedControl.selectedStainView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"stain.png"]]
  
        var selectedItem: UIView = h.items[h.selectedSegmentIndex] as! UIView;
       // h.selectedStainView.frame = CGRectMake(28.75,40,80,1)
        h.selectedStainView = UIImageView(image: UIImage(named: "选中.png"))
        h.backgroundColor = h.colorWithHexString("#ffffff")
        h.selectedSegmentTextColor = h.colorWithHexString("#0cac69")
        h.segmentTextColor = h.colorWithHexString("#646464")
        h.addTarget(self, action: Selector("valueChanged:"), forControlEvents: UIControlEvents.ValueChanged )
        self.view.addSubview(h)
        
        
 
        //子菜单
     
        if(h.selectedSegmentIndex == 0)
        {
            subMenu = CCSegmentedControl(items: ["最新","热门","好评","筛选"])
            
            //py  height 高度30 待适配
            subMenu.frame = CGRect(x: 0, y: 0, width: container.frame.width, height: 30)
            
            // CGRectMake(0, 112, 320, 30)
            //subMenu.selectedStainView = UIImageView(image:UIImage(named: "线2.png"))
            subMenu.backgroundColor = subMenu.colorWithHexString("#ffffff")
            subMenu.segmentTextColor = subMenu.colorWithHexString("#838383")
            subMenu.selectedSegmentTextColor = h.colorWithHexString("#0cac69")
            subMenu.addTarget(self, action: Selector("subMenuvalueChanged:"), forControlEvents: UIControlEvents.ValueChanged )
            
            
            //py 添加底部分隔线
            subMenu.backgroundImage = UIImage(named: "线.png")
            
            
          //  subMenu.selectedStainView.frame = CGRectMake(28.75,40,80,1)
           // subMenu.selectedStainView = UIImageView(image: UIImage(named: "选中.png"))
            
            
            container.addSubview(subMenu)
         //   container.pagingEnabled = true
                
                
                
                
                
               /*
                
                _contentScrollView.frame = CGRectMake(0,_topBarHeight + kYSLScrollMenuViewHeight, self.view.frame.size.width, self.view.frame.size.height - (_topBarHeight + kYSLScrollMenuViewHeight));
            _contentScrollView.backgroundColor = [UIColor clearColor];
            _contentScrollView.pagingEnabled = YES;
            _contentScrollView.delegate = self;
            _contentScrollView.showsHorizontalScrollIndicator = NO;
            _contentScrollView.scrollsToTop = NO;
            [self.view addSubview:_contentScrollView];
            _contentScrollView.contentSize = CGSizeMake(_contentScrollView.frame.size.width * self.childControllers.count, _contentScrollView.frame.size.height);
            
            // ContentViewController setup
            for (int i = 0; i < self.childControllers.count; i++) {
                id obj = [self.childControllers objectAtIndex:i];
                if ([obj isKindOfClass:[UIViewController class]]) {
                    UIViewController *controller = (UIViewController*)obj;
                    CGFloat scrollWidth = _contentScrollView.frame.size.width;
                    CGFloat scrollHeght = _contentScrollView.frame.size.height;
                    controller.view.frame = CGRectMake(i * scrollWidth, 0, scrollWidth, scrollHeght);
                    [_contentScrollView addSubview:controller.view];
                }
            }
*/
            
                
                
            
            self.showSubMenuBorder()
           
            //全部课程列表
            allcourse = UIStoryboard(name: "AllCourse", bundle: nil).instantiateViewControllerWithIdentifier("AllCourseViewController") as! AllCourseViewController
           allcourse.view.frame = CGRect(x: 0, y: 30, width: container.frame.width, height: container.frame.height)

//            container.addSubview(allcourse.view)
//            container.bringSubviewToFront(allcourse.view)
            
            self.addChildViewController(allcourse)
            container.addSubview(allcourse.view)
            allcourse.didMoveToParentViewController(self)
            self.containerSelected = allcourse

        }
        
        
        
  
        
        
        
        
        //var lineRec:uivew  = self.view.frame(CGRectMake(0,104, 320, 10))
        
        // Do any additional setup after loading the view, typically from a nib.
    }
    
  // - (void)valueChanged:(id)sender
    
        func showSubMenuBorder()
        {
            var pos:CGFloat = 0;
            var totalSubMenuWidth:CGFloat = 0;
            for var index = 0; index < subMenu.items.count ; index++
            {
                var itemWidth = CGRectGetWidth(subMenu.items[index].bounds);
                totalSubMenuWidth += itemWidth;
            }
            
            var spaceLeft:CGFloat = CGRectGetWidth(self.view.bounds) - totalSubMenuWidth;
            var interItemSpace:CGFloat = spaceLeft / (CGFloat)(subMenu.items.count + 1);
            
            for var index = 0; index < subMenu.items.count-1; index++
            {
                var subMenuBorderView = UIImageView(image: UIImage(named: "线2.png"))
                //subMenuBorderView.frame = CGRect(x: subMenu.items[index].frame.origin.x, y: 0, width: 1, height: subMenu.frame.size.height)
                if(index == 0)
                {
                    pos += interItemSpace + CGRectGetMaxX(subMenu.items[index].bounds) + interItemSpace/2
                }
                else
                {
                    pos += interItemSpace + CGRectGetMaxX(subMenu.items[index].bounds)
                }
                //pos = interItemSpace + CGRectGetMaxX(subMenu.items[index].bounds) + interItemSpace/2
                subMenuBorderView.frame = CGRect(x: pos, y: 0, width: 1, height: subMenu.frame.size.height)
                container.addSubview(subMenuBorderView)
            }
        }
    
        func subMenuvalueChanged(sender:CCSegmentedControl)
        {
            
            var subMenu:CCSegmentedControl = sender
            if(subMenu.selectedSegmentIndex == 0)
            {
                
                //全部课程列表
                DBUtils.mem.sortItem = 0
                container.bringSubviewToFront(allcourse.view)
                allcourse.tableView.header.beginRefreshing()
                
//                    allcourse = UIStoryboard(name: "AllCourse", bundle: nil).instantiateViewControllerWithIdentifier("AllCourseViewController") as! AllCourseViewController
//                    allcourse.view.frame = CGRect(x: 0, y: 30, width: container.frame.width, height: container.frame.height)
//               
//                container.addSubview(allcourse.view)
//                
//                container.bringSubviewToFront(allcourse.view)
                //transitionFromViewController(self.containerSelected!, toViewController: allcourse, duration: 0, options: nil, animations: nil, completion: nil)
                //self.containerSelected = allcourse
                
            }
            else if (subMenu.selectedSegmentIndex == 1)
            {
                DBUtils.mem.sortItem = 1
                container.bringSubviewToFront(allcourse.view)
                allcourse.tableView.header.beginRefreshing()
//                    allcourse = UIStoryboard(name: "AllCourse", bundle: nil).instantiateViewControllerWithIdentifier("AllCourseViewController") as! AllCourseViewController
//                    allcourse.view.frame = CGRect(x: 0, y: 30, width: container.frame.width, height: container.frame.height)
//                
//                container.addSubview(allcourse.view)
//                container.bringSubviewToFront(allcourse.view)
                //transitionFromViewController(self.containerSelected!, toViewController: allcourse, duration: 0, options: nil, animations: nil, completion: nil)
                //self.containerSelected = allcourse

                
            }
            else if (subMenu.selectedSegmentIndex == 2)
            {
                DBUtils.mem.sortItem = 2
                container.bringSubviewToFront(allcourse.view)
                allcourse.tableView.header.beginRefreshing()
//                
//                    allcourse = UIStoryboard(name: "AllCourse", bundle: nil).instantiateViewControllerWithIdentifier("AllCourseViewController") as! AllCourseViewController
//                    allcourse.view.frame = CGRect(x: 0, y: 30, width: container.frame.width, height: container.frame.height)
//               
//                container.addSubview(allcourse.view)
//                
//                container.bringSubviewToFront(allcourse.view)
                //transitionFromViewController(self.containerSelected!, toViewController: allcourse, duration: 0, options: nil, animations: nil, completion: nil)
                //self.containerSelected = allcourse

            }
            else if (subMenu.selectedSegmentIndex == 3)
            {
                
                
            //    vw.frame = CGRect(x: 0, y: 30, width: container.frame.width, height: 300)
                
                
                
                var x = vw.frame.width
              //  x -= 120
               // x = x/2
             
                vw.frame = CGRectMake(0,416,320,40)
                vw.backgroundColor = UIColor.whiteColor()
                
                var filterbutton:UIButton = UIButton(frame: CGRectMake(x-100, 0, 80, 30))
               // filterbutton.frame =  CGRectMake(0,0,320,40)
                
                filterbutton.layer.backgroundColor = UIColor(red: 241, green: 241, blue: 241, alpha: 1).CGColor
                
                filterbutton.titleLabel?.font = UIFont.systemFontOfSize(18)
                filterbutton.titleLabel?.textColor = UIColor(red: 51, green: 51, blue: 51, alpha: 1)
                vw.addSubview(filterbutton)
                filterbutton.setTitleColor(UIColor.whiteColor(),forState:UIControlState.Normal)
                filterbutton.setTitle("确认", forState:UIControlState.Normal)
                filterbutton.setBackgroundImage(UIImageView(image: UIImage(named: "导航.png")).image, forState: UIControlState.Normal)
                
                
                filterbutton.addTarget(self, action:Selector("filterbuttonClicked:"), forControlEvents:UIControlEvents.TouchDown)
                
                
                
                
                var resetbutton:UIButton = UIButton(frame: CGRectMake(x-200, 0, 80, 30))
                // filterbutton.frame =  CGRectMake(0,0,320,40)
                
                resetbutton.layer.backgroundColor = UIColor(red: 241, green: 241, blue: 241, alpha: 1).CGColor
                
                resetbutton.titleLabel?.font = UIFont.systemFontOfSize(18)
                resetbutton.titleLabel?.textColor = UIColor(red: 51, green: 51, blue: 51, alpha: 1)
                vw.addSubview(filterbutton)
                resetbutton.setTitleColor(UIColor.whiteColor(),forState:UIControlState.Normal)
                resetbutton.setTitle("重置", forState:UIControlState.Normal)
                resetbutton.setBackgroundImage(UIImageView(image: UIImage(named: "导航.png")).image, forState: UIControlState.Normal)
                
                
                resetbutton.addTarget(self, action:Selector("resetbuttonClicked:"), forControlEvents:UIControlEvents.TouchDown)
                
                
                   vw.addSubview(resetbutton)
                
                
               //  h.addTarget(self, action: Selector("valueChanged:"), forControlEvents: UIControlEvents.ValueChanged )
                
                
               // [filterbutton addTarget:self action:@selector(filterbuttonClicked:) forControlEvents:UIControlEventTouchDown];
                

            
                
                if(classifyMenuViewController == nil){
                    classifyMenuViewController = UIStoryboard(name: "AllCourse", bundle: nil).instantiateViewControllerWithIdentifier("CYLClassifyMenuViewController") as! CYLClassifyMenuViewController
                    classifyMenuViewController.view.frame = CGRect(x: 0, y: 30, width: container.frame.width, height: container.frame.size.height)
                }
                
                container.addSubview(classifyMenuViewController.view)
           
                container.addSubview(vw)

                
                container.bringSubviewToFront(classifyMenuViewController.view)
                container.bringSubviewToFront(vw)
            }
            
    }

    func filterbuttonClicked(sender:UIButton)
    {
        //筛选结果
        subMenu.selectedSegmentIndex = 3
        DBUtils.mem.sortItem = 3
        allcourse.tableView.header.beginRefreshing()
        
        container.bringSubviewToFront(allcourse.view)
//        allcourse = UIStoryboard(name: "AllCourse", bundle: nil).instantiateViewControllerWithIdentifier("AllCourseViewController") as! AllCourseViewController
//        allcourse.view.frame = CGRect(x: 0, y: 30, width: container.frame.width, height: container.frame.height)
//        container.addSubview(allcourse.view)
//        container.bringSubviewToFront(allcourse.view)
  
    }
    
    
    func resetbuttonClicked(sender:UIButton)
    {
        //重置按钮
        GlobalData.grade.removeAllObjects()
        GlobalData.edition.removeAllObjects()
        GlobalData.topic.removeAllObjects()
        classifyMenuViewController.viewDidLoad()

    }
    
    
    
    
    
    
    func valueChanged(sender:CCSegmentedControl)
    {
        var h:CCSegmentedControl = sender
        
       // UIView *selectedItem = self.items[self.selectedSegmentIndex];
       // h.selectedStainView.frame = CGRectMake(selectedItem.frame.origin.x-10,40,selectedItem.frame.size.width+20,1);
  //      h.selectedStainView.frame = CGRectMake(h.selectedSegmentIndex.frame.origin.x-10,40,h.selectedSegmentIndex.frame.size.width+20,1);
     
        var selectedItem: UIView = h.items[h.selectedSegmentIndex] as! UIView;
         h.selectedStainView.frame = CGRectMake(selectedItem.frame.origin.x-10,40,selectedItem.frame.size.width+20,1);
   
        if(h.selectedSegmentIndex == 0 && self.containerSelected != allcourse)
        {
            //子菜单
            
            container.bringSubviewToFront(subMenu)
//            container.addSubview(subMenu)
            self.showSubMenuBorder()
            
            //全部课程列表
            if(allcourse == nil)
            {
                allcourse = UIStoryboard(name: "AllCourse", bundle: nil).instantiateViewControllerWithIdentifier("AllCourseViewController") as! AllCourseViewController
                allcourse.view.frame = CGRect(x: 0, y: 30, width: container.frame.width, height: container.frame.height)
            }
            
            
           // allcourse.tableView.pagingEnabled = true

//            container.addSubview(allcourse.view)
//           container.bringSubviewToFront(allcourse.view)
            
            transitionFromViewController(self.containerSelected!, toViewController: allcourse, duration: 0, options: nil, animations: nil, completion: nil)
            self.containerSelected = allcourse

            
        }
        else if (h.selectedSegmentIndex == 1 && self.containerSelected != learncourse)
        {
            //DbPreference.memNames.loginStatus = true
            if (DBUtils.mem.loginStatus) {
                if(learncourse == nil){
                    learncourse = UIStoryboard(name: "LearnCourse", bundle: nil).instantiateViewControllerWithIdentifier("LearnCourse") as! LearnCourse
                    learncourse.view.frame = CGRect(x: 0, y: 0, width: container.frame.width, height: container.frame.height)
                    self.addChildViewController(learncourse)
                    learncourse.didMoveToParentViewController(self)
                    }else{
                    //              allcourse.ReloadData()
                }
                
                transitionFromViewController(self.containerSelected!, toViewController: learncourse, duration: 0, options: nil, animations: nil, completion: nil)
                self.containerSelected = learncourse
//                container.addSubview(learncourse.view)
//                container.bringSubviewToFront(learncourse.view)
                
            } else {
                var viewController = UIStoryboard(name: "Login", bundle: nil).instantiateViewControllerWithIdentifier("Login") as! LoginViewController
                viewController.sourceNavi = false
                
                rootController.navigationController?.pushViewController(viewController,animated:true)
                self.navigationController?.setNavigationBarHidden(false, animated: true)
                
            }

            
        }
        else if (h.selectedSegmentIndex == 2 && self.containerSelected != finishedcourse)
        {
            if (DBUtils.mem.loginStatus) {
                if(finishedcourse == nil)
                {
                    finishedcourse = UIStoryboard(name:"finishedCourse", bundle: nil).instantiateViewControllerWithIdentifier("finishedCourse") as! finishedCourse
                    finishedcourse.view.frame = CGRect(x: 0, y: 0, width: container.frame.width, height: container.frame.height)
                    self.addChildViewController(finishedcourse)
                    finishedcourse.didMoveToParentViewController(self)
                    
                }
                else{
                    //              allcourse.ReloadData()
                }
                
                
                transitionFromViewController(self.containerSelected!, toViewController: finishedcourse, duration: 0, options: nil, animations: nil, completion: nil)
                self.containerSelected = finishedcourse
//                container.addSubview(finishedcourse.view)
//                container.bringSubviewToFront(finishedcourse.view)
                
            } else {
                var viewController = UIStoryboard(name: "Login", bundle: nil).instantiateViewControllerWithIdentifier("Login") as! LoginViewController
                viewController.sourceNavi = false
                
                rootController.navigationController?.pushViewController(viewController,animated:true)
                self.navigationController?.setNavigationBarHidden(false, animated: true)
                
//                if (DBUtils.mem.loginStatus) {
//                    
//                    finishedcourse = UIStoryboard(name: "finishedCourse", bundle: nil).instantiateViewControllerWithIdentifier("finishedCourse")
//                        as! finishedCourse
//                    container.addSubview(finishedcourse.view)
//                    container.bringSubviewToFront(finishedcourse.view)
//                }
                
                
                
            }

           
            
          
        }



       /* var subMenu = CCSegmentedControl(items: ["最新","热门","价格","筛选"])
        subMenu.frame = CGRectMake(0, 114, 320, 30)
        //subMenu.selectedStainView = UIImageView(image:UIImage(named: "线2.png"))
        
        subMenu.backgroundColor = h.colorWithHexString("#ffffff")
        subMenu.segmentTextColor = h.colorWithHexString("#838383")
        subMenu.addTarget(self, action: Selector("subMenuvalueChanged:"), forControlEvents: UIControlEvents.ValueChanged )

        
        if(h.selectedSegmentIndex == 0)
        {
            
            self.view.addSubview(subMenu)
        }
        else if(h.selectedSegmentIndex == 1)
        {
            subMenu.removeFromSuperview()
            //self.view.removeFromSuperview()
            
        }*/
        
        
   // CCSegmentedControl* segmentedControl = sender;
   // NSLog(@"%s line:%d segment has changed to %d", __FUNCTION__, __LINE__, segmentedControl.selectedSegmentIndex);
    }

    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    
    
}



